<template>
  <div>
    <el-dialog
      title="关联班级"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="1000px"
    >
      <el-form :model="classForm" ref="classForm" label-width="80px">
        <el-row
          :gutter="10"
          v-for="(item, index) in classForm.gradeClass"
          :key="index"
        >
          <el-col :span="7">
            <el-form-item
              label="年级："
              :prop="'gradeClass.' + index + '.grade'"
              :rules="[
                { required: true, message: '请选择年级', trigger: 'change' }
              ]"
            >
              <nice-select
                v-model="item.grade"
                placeholder="请选择年级"
                clearable
                :options="selectEnums.grade"
                labelkey="name"
                valuekey="id"
                @change="changeGrade(index)"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
              label="班级："
              :prop="'gradeClass.' + index + '.classId'"
              :rules="[
                { required: true, message: '请选择班级', trigger: 'change' }
              ]"
            >
              <nice-select
                v-model="item.classId"
                placeholder="请选择班级"
                clearable
                :options="item.classList"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
              label="科目："
              :prop="'gradeClass.' + index + '.subject'"
              :rules="[
                { required: true, message: '请选择科目', trigger: 'change' }
              ]"
            >
              <nice-select
                v-model="item.subject"
                placeholder="请选择科目"
                clearable
                labelkey="name"
                valuekey="id"
                :options="selectEnums.subject"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="margin-top10">
            <i
              class="el-icon-delete"
              @click="deleteContract(item, index)"
              v-if="index !== 0"
            ></i>
          </el-col>
        </el-row>
      </el-form>
      <div class="center">
        <el-button
          type="text"
          icon="el-icon-circle-plus"
          size="small"
          @click="addRelatedClass()"
          >添加关联班级</el-button
        >
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAllRelated" size="small"
          >取消全部关联</el-button
        >
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="dataFormSubmit"
          size="small"
          v-preventReClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { cascadeQuery, tableInsert, tableDeleted } from '@/api/api.js'
import {
  adminschoolclasseslist,
  adminschoolteacheraddClass,
  adminschoolteacherclearClass,
  adminschoolteacheraddSubjectClass
} from '@/api/lcmapi.js'
export default {
  data () {
    return {
      visible: false,
      teacherId: '',
      classForm: {
        gradeClass: [
          {
            grade: '',
            class: '',
            classList: []
          }
        ]
      }
    }
  },
  props: {
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    gradeList: {
      type: Array,
      default: function () {
        return []
      }
    },
    schoolId: ''
  },
  methods: {
    init (row) {
      this.visible = true
      this.teacherId = row.teacherId || 0
      this.classesList = row.classesList
      this.$nextTick(() => {
        this.$refs['classForm'].clearValidate()
        this.$refs['classForm'].resetFields()
        if (row.classesList && row.classesList[0]) {
          let relateList = row.classesList
          this.classForm.gradeClass = relateList.map((item, index) => {
            return {
              grade: +item.grade,
              classId: +item.classId,
              subject: +item.subject,
              classList: [
                {
                  label: item.className,
                  value: +item.classId
                }
              ]
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['classForm'].validate(valid => {
        if (valid) {
          this.submit()
        }
      })
    },
    async changeGrade (index) {
      let classList = []
      this.classForm.gradeClass[index].class = null
      let res = await adminschoolclasseslist({
        schoolId: this.schoolId,
        grade: this.classForm.gradeClass[index].grade
      })
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        if (res[1].data && res[1].data.length) {
          res[1].data.forEach(ele => {
            classList.push({
              label: ele.className,
              value: ele.id
            })
          })
        }
        this.$set(this.classForm.gradeClass, index, {
          class: '',
          grade: this.classForm.gradeClass[index].grade,
          classList: classList
        })
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async submit () {
      let classesList = [...new Set(this.classForm.gradeClass)]
      let res = await adminschoolteacheraddSubjectClass({
        teacherId: this.teacherId,
        schoolId: this.schoolId,
        classesList: classesList
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message.success('关联班级成功！')
        this.visible = false
        this.$emit('refreshDataList')
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async closeAllRelated () {
      this.$confirm('是否确认取消全部关联', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await adminschoolteacherclearClass({
            teacherId: this.teacherId,
            schoolId: this.schoolId
          })
          if (res[0]) {
            return
          }
          let data = res[1]
          if (data && data.code === 0) {
            this.$message.success('全部取消关联成功！')
            this.visible = false
            this.$emit('refreshDataList')
          } else {
            this.$message.error(res[1].msg)
          }
        })
        .catch(() => {})
    },
    deleteContract (item, index) {
      this.classForm.gradeClass.splice(index, 1)
    },
    addRelatedClass () {
      this.classForm.gradeClass.push({ grade: '', classId: '', subject: '' })
    }
  }
}
</script>
